﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using System.Data;
using System.Xml;
using System.Xml.Xsl;
using System.Text;

public partial class PayBlance : ExtBaseRpt
{
    string mid;
    protected void Page_Load(object sender, EventArgs e)
    {
        this.txtshop.GetStore().DataSource = db.DM_GetDateSet("select shopid,shopname from bas_shop order by shopcode");
        mid = Request.Params["mid"];
        if (!X.IsAjaxRequest)
        {
            //BuildGridPanel(this.GridPanel1, mid, Session["UserID"].ToString());
            this.txtbdate.Text = DateTime.Now.ToString();
            InsActLog(mid, "浏览");
            this.txtedate.Text = DateTime.Now.ToString();
            CheckEventsRight(mid);
            //this.txtbjhdate.Text = DateTime.Now.ToString("yyyy-MM-01");
            //this.txtejhdate.Text = DateTime.Now.ToString();
        }
    }
    protected void CheckEventsRight(string mid)
    {
        string sql = @"select a.WebUrl,isnull(r.M_Browse,0)as isbrowse from Sys_Modules a
                        left join Sys_ModuleRights r on r.mid = a.mid and userid="+Session["UserID"]+" where ModuleType = 5 and ParentId ="+mid;
        DataSet ds = mydb.DM_GetDateSet(sql);
        if (ds != null && ds.Tables.Count > 0)
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                if (dr["weburl"].ToString() != "")
                {
                    if (FindControl(dr["WebUrl"].ToString()) != null)
                    {
                        if (dr["isbrowse"].ToString() == "True")
                            ((Ext.Net.Button)FindControl(dr["WebUrl"].ToString())).Visible = true;
                        else
                            ((Ext.Net.Button)FindControl(dr["WebUrl"].ToString())).Visible = false;
                    }
                }
            }
        }
    }
    [DirectMethod(Namespace = "CompanyX")]
    public void binStock(string area)
    {
       
    }
    protected void BtnQureyUser(object sender, DirectEventArgs e)
    {
        string str = "";
        if (txtstates.Value.ToString() != "0")
        {
            if (txtstates.Value.ToString() == "1")
            {
                str = " and a.cwstate = '已确认'";
            }
            else if (txtstates.Value.ToString() == "2")
            {
                str = " and a.dzstate = '已打款'";
            }
            else
            {
                str = " and a.clstate = '已确认'";
            }
        }
        string sql = "select * from V_CustomerAccountDtl a "
                +"inner join V_Shop s on s.ShopCode = a.ShopCode "
                + "inner join Sys_UserDataRights u on u.SourceID = s.StockID where u.userid = " + Session["UserID"] + " and a.saledate between '"
            + txtbdate.Text + "' and '" + txtedate.Text + "'" + (txtshop.Text != "" ? " and a.shopcode = '"+txtshop.Text+"'" : " ")
            + (txtqshop.Text != "" ? " and (a.shopcode like '%" + txtqshop.Text + "%' or a.shopname like '%" + txtqshop.Text + "%')" : " " + str);
        this.Store1.DataSource = mydb.DM_GetDateSet(sql);
        this.Store1.DataBind();
        //DynaGridResult(ds);
    }
    protected void Btntest(object sender, DirectEventArgs e)
    {
        AppCan app = new AppCan();
        //RowSelectionModel sm = this.GridPanel1.GetSelectionModel() as RowSelectionModel;
        string shopcode = this.Hf_ShopCode.Value.ToString();
        DataSet ds = mydb.DM_GetDateSet(@"select a.UserID,UserName,SourceName from Sys_UserDataRights a 
                                            inner join V_Shop v on v.ShopID = a.SourceID
                                            inner join Sys_LoginUser u on u.UserID = a.UserID and u.isApp=1
                                            where v.ShopCode='" + shopcode + "'");
        string userlist="";
        foreach(DataRow dr in ds.Tables[0].Rows){
            userlist += "\""+dr["UserID"]+"\",";
        }
        app.JPrushSendMsg("日结对账单", "您今天有新的对账单，请注意查看！", userlist.TrimEnd(','));
    }
    protected void BtnCheckList(object sender, DirectEventArgs e)
    {
        string sql = @"select ShopCode,saledate,endAmount,0,sjpayclamt,sjpayclamt2,0,1,'',getdate(),null,null,'' from V_CustomerAccountDtl " +
        " where saledate between '" + txtbdate.Text + "' and '" + txtedate.Text + "' and cwstate = '未确认'";
        if (mydb.DM_GetDateSet(sql).Tables[0].Rows.Count == 0)
        {
            ShowBox("本期没有帐单需要确认！");
            return;
        }
        sql=@"insert into KM_Shops_StateMent 
        select ShopCode,saledate,endAmount,0,sjpayclamt,sjpayclamt2,0,1,'',getdate(),null,null,0,null,'' from V_CustomerAccountDtl "+
        " where saledate between '"+txtbdate.Text+"' and '"+txtedate.Text+"' and cwstate = '未确认'";
        //ShowBox(sql);
        if (mydb.DM_ExecuteNonQuery(sql) != -1)
        {
            ShowBox("全部确认成功！");
            BtnQureyUser(null, null);
        }
    }
    protected void BtnShowImg(object sender, DirectEventArgs e)
    {
        //RowSelectionModel sm = this.GridPanel1.GetSelectionModel() as RowSelectionModel;
        string shopcode = this.Hf_ShopCode.Value.ToString();
        string sql = "select '<img style=\"width:180px;height:180px;\" src=\"..'+url+'\" />'as imgulr from Bas_ShopReceiptImg where ShopCode='" 
            + shopcode + "' and paydate ='"+this.Hf_PayDate.Value.ToString()+"'";
        DataSet ds = mydb.DM_GetDateSet(sql);
        this.Store2.DataSource = ds;
        this.Store2.DataBind();
        this.Window2.Show();
    }
        //财务打款
    protected void BtnCwpay(object sender, DirectEventArgs e)
    {
        if (this.txtpaymoney.Text == "")
        {
            ShowBox("打款金额不能为空！");
            return;
        }
        
        //RowSelectionModel sm = this.GridPanel1.GetSelectionModel() as RowSelectionModel;
        string shopcode = this.Hf_ShopCode.Value.ToString();
        if (mydb.DM_GetDateSet("select *from KM_Shops_StateMent where shopcode='" + shopcode + "' and recondate ='"+txtbdate.Text+"' and cwstate=1").Tables[0].Rows.Count > 0)
        {
            ShowBox("无法操作，财务已确认！");
            return;
        }
        string sql = @"insert into KM_Shops_StateMent
                        select shopcode,saledate,endAmount,PeriAmount,sjpayclamt,"+this.txtpaymoney.Text+",0,1,'"+Session["UserCode"]+@"',getdate(),null,getdate(),1,getdate(),''
                        from [dbo].[V_CustomerAccountDtl] where ShopCode='"+shopcode+"' and saledate='"+this.txtbdate.Text+"'";
        if (mydb.DM_ExecuteNonQuery(sql) != -1)
        {
            mydb.DM_ExecuteNonQuery("insert into Bas_Payment values('"+shopcode+"','"+Session["UserCode"]+"',"+this.txtpaymoney.Text+",'"+this.txtbdate.Text+"')");
            this.Window1.Hide();
            BtnQureyUser(null, null);
        }
        else
        {
            ShowBox("操作失败！");
        }
    }
    //生成对帐单
    protected void BtnCreateAcc(object sender, DirectEventArgs e)
    {
        if (txtbdate.Text != txtedate.Text)
        {
            ShowBox("时间范围必须设置为1天！");
            return;
        }
        if (Convert.ToDateTime(txtbdate.Text).ToString("yyyy-MM-dd") == DateTime.Now.ToString("yyyy-MM-dd"))
        {
            ShowBox("不能生成当日对账单！");
            return;
        }
        string sql = "select * from V_CustomerAccountDtl where saledate between '"
            + txtbdate.Text + "' and '" + txtedate.Text + "'" + (txtshop.Text != "" ? " and shopcode = '" + txtshop.Text + "'" : " ");
        if (mydb.DM_GetDateSet(sql).Tables[0].Rows.Count > 0)
        {
            ShowBox("当前对账单已生成，请不要重复操作！");
            return;
        }
        sql = "select top 1 * from V_CustomerAccountDtl where cwstate='未确认' and saledate <= '"
            + Convert.ToDateTime(txtbdate.Text).AddDays(-1).ToString("yyyy-MM-dd") + "'";
        if (mydb.DM_GetDateSet(sql).Tables[0].Rows.Count > 0)
        {
            ShowBox("上期账单还未确认，无法生成本期帐单！");
            return;
        }
        sql = "select top 1 * from V_CustomerAccountDtl where saledate >= '"
            + Convert.ToDateTime(txtbdate.Text).AddDays(+1).ToString("yyyy-MM-dd") + "'";
        if (mydb.DM_GetDateSet(sql).Tables[0].Rows.Count > 0)
        {
            ShowBox("无法生成小于" + Convert.ToDateTime(txtbdate.Text).AddDays(+1).ToString("yyyy-MM-dd") + "的帐单！");
            return;
        }
        string bdate, edate;
        if (Convert.ToDateTime(txtbdate.Text) == Convert.ToDateTime("0001-01-01 00:00:00"))
            bdate = "";
        else
            bdate = txtbdate.Text;

        if (Convert.ToDateTime(txtedate.Text) == Convert.ToDateTime("0001-01-01 00:00:00"))
            edate = "";
        else
            edate = txtedate.Text;
        string shop = StrSplitParam(txtshop);
        if (db.DM_ExecuteNonQuery("KM_ShopBlanceAcc_Rtp '" + bdate + "','" + edate + "','" + shop + "'") != -1)
        {
            ShowBox("生成成功！");
        }
        else
        {
            ShowBox("生成失败，请核查！");
        }
        BtnQureyUser(null,null);
    }
    protected void BtnDeleteAcc(object sender, DirectEventArgs e)
    {
        string sql = "";
        sql = " select top 1 * from KM_Shops_StateMent where isnull(clstate,0)=1 and recondate between '"
           + txtbdate.Text + "' and '" + txtedate.Text + "'" + (txtshop.Text != "" ? " and shopcode = '" + txtshop.Text + "'" : " ");
        if (mydb.DM_GetDateSet(sql).Tables[0].Rows.Count > 0)
        {
            ShowBox("当前对账单已经被加盟商确认，无法删除！");
            return;
        }
        sql = "delete from KM_CustomerAccountDtl where saledate between '"
            + txtbdate.Text + "' and '" + txtedate.Text + "'" + (txtshop.Text != "" ? " and shopcode = '" + txtshop.Text + "'" : " ");
        sql += " delete from KM_Shops_StateMent where recondate between '"
           + txtbdate.Text + "' and '" + txtedate.Text + "'" + (txtshop.Text != "" ? " and shopcode = '" + txtshop.Text + "'" : " ");
        sql += " delete from Bas_Payment where paydate between '"
           + txtbdate.Text + "' and '" + txtedate.Text + "'" + (txtshop.Text != "" ? " and shopcode = '" + txtshop.Text + "'" : " ");
        if (mydb.DM_ExecuteNonQuery(sql) != -1)
        {
            ShowBox("删除成功！");
        }
        else
        {
            ShowBox("删除失败，请核查！");
        }
        BtnQureyUser(null, null);
    }

    #region 动态加载报表显示结果
    private void DynaGridResult(DataSet ds)
    {
        if (ds == null) return;

        Store store = this.Store1;
        GridPanel grid = this.GridPanel1;
        store.Reader.Clear();
        grid.ColumnModel.Columns.Clear();
        store.Model.Clear();
       
        Model md = new Model();
        List<ColumnBase> list = new List<ColumnBase>();

        DataTable dt = ds.Tables[0];
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            //根据结果集创建Store
            ModelField field = new ModelField();
            field.Name = dt.Columns[i].ToString();
            md.Fields.Add(field);
            //创建grid colums
            Column cl = new Column();
            cl.Text = dt.Columns[i].ToString();
            cl.DataIndex = dt.Columns[i].ToString();
            list.Add(cl);
        }
        store.Model.Add(md);
        store.DataSource = ds;
        store.DataBind();
        grid.ColumnModel.Columns.Add(list);
        grid.Render();
    }
    #endregion
    protected void RefreshDataSet(object sender, StoreReadDataEventArgs e)
    {
        BtnQureyUser(null,null);
    }
    protected void Store1_Submit(object sender, StoreSubmitDataEventArgs e)
    {
        //导出EXCEL
        ExtGridToExcel(mid,"xls",e.Xml,this.Response,this.Title);
    }
    protected void ToExcel(object sender, EventArgs e)
    {
        InsActLog(mid, "导出");
        string json = this.Hidden1.Value.ToString();
        StoreSubmitDataEventArgs eSubmit = new StoreSubmitDataEventArgs(json, null);
        XmlNode xml = eSubmit.Xml;

        this.Response.Clear();
        this.Response.ContentType = "application/vnd.ms-excel";
        this.Response.AddHeader("Content-Disposition", "attachment; filename=" + this.Title + ".xls");

        XslCompiledTransform xtExcel = new XslCompiledTransform();

        xtExcel.Load(Server.MapPath("Excel.xsl"));
        xtExcel.Transform(xml, null, this.Response.OutputStream);
        this.Response.End();
    }
    protected void BtnCwCheck(object sender, DirectEventArgs e)
    {
        string shopcode = e.ExtraParams["shopcode"];
        string payclamt = e.ExtraParams["payclamt"];
    }
    [DirectMethod(Namespace = "CompanyX")]
    public void CwCheck(string shopcode,string saledte, string payclamt,string bgamt, string sjpayclamt,string shoppayamt,string endamt)
    {
        //string PeriAmount="0";
        //string beginAmount="0";
        //if (sjpayclamt=="0" && bgamt=="0"){
        //    PeriAmount = payclamt;
        //}
        //if (Convert.ToDouble(bgamt) > Convert.ToDouble(payclamt))
        //{
        //    beginAmount = payclamt;
        //}
        //else
        //{
        //    beginAmount = bgamt;
        //}
        if (mydb.DM_GetDateSet("select *from KM_Shops_StateMent where shopcode='" 
            + shopcode + "' and recondate ='" + saledte.Substring(1, 10) + "'").Tables[0].Rows.Count == 0)
        {
            ShowBox("无法操作，帐单未确认！");
            return;
        }
        if (mydb.DM_GetDateSet("select *from Bas_ShopReceiptImg where shopcode='" 
            + shopcode + "' and paydate ='" + saledte.Substring(1, 10) + "'").Tables[0].Rows.Count == 0)
        {
            ShowBox("无法操作，店铺没有上传小票！");
            return;
        }
        if (mydb.DM_GetDateSet("select *from KM_Shops_StateMent where shopcode='" 
            + shopcode + "' and recondate ='" + saledte.Substring(1, 10) + "' and ImgRed=1").Tables[0].Rows.Count > 0)
        {
            ShowBox("请不要重复操作！");
            return;
        }

        string sql = "insert into KM_Shops_StateMent values('"
                                    + shopcode + "','" 
                                    + saledte.Substring(1, 10) + "',"
                                    + endamt + ","
                                    + bgamt + ","
                                    + sjpayclamt + ","
                                    + shoppayamt+",0,1,'" 
                                    + Session["UserCode"] 
                                    + "',getdate(),null,null,'')";
        //财务查看小票确认
        sql = "update KM_Shops_StateMent set PeriAmount = "+endamt+",CurrAmount = '" + sjpayclamt 
            + "',CurrAmount2= " + shoppayamt + ",ImgRed = 1,RedDate = getdate() where shopcode='"
            + shopcode + "' and recondate ='" + saledte.Substring(1, 10) + "'";
        if (mydb.DM_ExecuteNonQuery(sql) != -1)
        {
            ShowBox("操作成功！");
            SendDayMsg(shopcode);
        }
        else
        {
            ShowBox("操作失败！");
        }
        BtnQureyUser(null, null);
    }
    protected void SendDayMsg(string shopcode)
    {
        AppCan app = new AppCan();
        DataSet ds = mydb.DM_GetDateSet(@"select a.UserID,UserName,SourceName from Sys_UserDataRights a 
                                            inner join V_Shop v on v.StockID = a.SourceID
                                            inner join Sys_LoginUser u on u.UserID = a.UserID and u.isApp=1
                                            where v.ShopCode='" + shopcode + "'");
        string userlist = "";
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            userlist += "\"" + dr["UserID"] + "\",";
        }
        app.JPrushSendMsg("日结对账单", "您今天有新的对账单，请注意查看！", userlist.TrimEnd(','));
    }
}